var num = 0;
var deviceCookieNum = 1;


$(function () {
// enterprise= sessionStorage.getItem("enterprise");
    loadDeviceType($('#deviceType-select'));
    if ($.cookie("deviceCookieNum")) {
        deviceCookieNum = $.cookie("deviceCookieNum");
        loadDeviceListData(deviceCookieNum);
    } else {
        loadDeviceListData();
    }

    userInfo($('#userInfo'));
});

function rNum(e) {
    num = e;
    loadDeviceListData();
}

$('#sort_param').change(function () {
    loadDeviceListData();
});
$('#deviceType-select').change(function () {
    loadDeviceListData();
});

function loadDeviceListData(_pageIndex) {
    var pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    $('#device_List').empty();
    showLoading(LOADING);
    getJson("/deviceData/getDeviceList", {
        "param": $('#param_id').val(),
        num: num,
        sortParam: $('#sort_param').val(),
        deviceType: $('#deviceType-select').val(),
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (data) {
        var result = data['payload']['data'];
        var payload = data['payload'];
        var pages = data['payload']['pages'];
        var total = data['payload']['total'];
        if (pageIndex > payload['pages']) {
            pageIndex = 1;
            $.cookie("deviceCookieNum", pageIndex, {path: '/'});
        }
        /*if (result.length == 1 && num==0) {
            location.href = 'deviceData.html?deviceId=' + result[0].id;
        } else {*/
        getJson("/deviceData/countDeviceStatusByParam", {
            param: $('#param_id').val(),
            deviceType: $('#deviceType-select').val()
        }, 'GET', function (data) {
            var c1 = 0;
            var c2 = 0;
            var c3 = 0;
            var c4 = 0;
            for (var i = 0; i < data.length; i++) {
                var dd = data[i];
                if (dd.date == 1) {
                    c1 = dd.value;
                }
                if (dd.date == 2) {
                    c2 = dd.value;
                }
                if (dd.date == 3) {
                    c3 = dd.value;
                }
                if (dd.date == 4) {
                    c4 = dd.value;
                }
            }
            var count = c1 + c2 + c3 + c4;
            $('#btCount').text(count);
            $('#bt1').text(c1);
            $('#bt2').text(c2);
            $('#bt3').text(c3);
            $('#bt4').text(c4);
        })
        $('#device_List').empty();
        for (var i = 0; i < result.length; i++) {
            var iLabel = '';
            switch (result[i].status) {
                case 1:
                    iLabel = ' <i class="iconfont icon-gongzuo text-powerOn"></i>\n' +
                        '<i class="iconfont icon-gongzuo mx-3 text-standby text-grey"></i>\n' +
                        '<i class="iconfont icon-gongzuo text-powerOff text-grey"></i>\n' +
                        '<i class="iconfont icon-gongzuo ml-3 text-fault text-grey"></i>';
                    break;
                case 2:
                    iLabel = '                <i class="iconfont icon-gongzuo text-powerOn text-grey"></i>\n' +
                        '                <i class="iconfont icon-gongzuo mx-3 text-standby"></i>\n' +
                        '                <i class="iconfont icon-gongzuo text-powerOff text-grey"></i>\n' +
                        '                <i class="iconfont icon-gongzuo ml-3 text-fault text-grey"></i>';
                    break;
                case 3:
                    iLabel = '                <i class="iconfont icon-gongzuo text-powerOn text-grey"></i>\n' +
                        '                <i class="iconfont icon-gongzuo mx-3 text-standby text-grey"></i>\n' +
                        '                <i class="iconfont icon-gongzuo text-powerOff"></i>\n' +
                        '                <i class="iconfont icon-gongzuo ml-3 text-fault text-grey"></i>';
                    break;
                case 4:
                    iLabel = '                <i class="iconfont icon-gongzuo text-powerOn text-grey"></i>\n' +
                        '                <i class="iconfont icon-gongzuo mx-3 text-standby text-grey"></i>\n' +
                        '                <i class="iconfont icon-gongzuo text-powerOff text-grey"></i>\n' +
                        '                <i class="iconfont icon-gongzuo ml-3 text-fault"></i>';
                    break;
            }
            var health = 0;
            if (result[i]['health']) {
                health = result[i]['health'];
            }
            var deviceType = '';
            if (result[i]['typeOneName']) {
                deviceType += result[i]['typeOneName'];
                if (result[i]['typeTowName']) {
                    deviceType += '/' + result[i]['typeTowName'];
                    if (result[i]['typeThreeName']) {
                        deviceType += '/' + result[i]['typeThreeName'];
                    }
                }
            }
            var str = '<div class="device-list" id="tr_' + (i + 1) + '">\n' +
                '<div class="centent">\n' +
                '<div class="d-flex">\n' +
                '<div>' +
                '<div class="device-img-wrapper align-items-center justify-content-center d-flex" onclick=\"viewDeviceInfo(' + result[i].id + ')\" title="查看基本信息">\n' +
                '<img class="img-fluid" src="' + fileUrl + concatMinImgUrl(result[i].image) + '" data-origin="' + fileUrl + result[i].image + '" alt="加载失败" onerror="deviceImgError(this)">\n' +
                '</div>\n' +
                '<div class="mt-3 font-p16">\n' +
                iLabel +
                '</div>\n' +
                '</div>\n' +
                '<div class="flex-1 ml-4">\n' +
                '<div class="font-p14 text-emphasize mb-2 d-flex align-items-center">名称 <span class="font-p16 text-white ml-2 text-truncate" style="width: 6em; display: inline-block;">' + result[i].name + '</span></div>\n' +
                '<div class="font-p14 text-emphasize mb-2 d-flex align-items-center">类型 <span class="font-p16 text-white ml-2 text-truncate" style="width: 6em; display: inline-block;">' + deviceType + '</span></div>\n' +
                '<div class="font-p14 text-emphasize mb-2 d-flex align-items-center">编号 <span class="font-p16 text-white ml-2 text-truncate" style="width: 6em; display: inline-block;">' + result[i].sn + '</span></div>\n' +
                '<div class="font-p14 text-emphasize d-flex align-items-center">时长 <span class="font-p16 text-white ml-2 text-truncate" style="width: 6em; display: inline-block;">' + Math.round(result[i].productionTime * 100) / 100 + 'h</span></div>\n' +

                '</div>\n' +
                '</div>\n' +
                '<div class="d-flex justify-content-around" style="margin-top: 20px;">\n' +
                '<div class="text-center flex-1">\n' +
                '<div class="font-p12 mb-1">用电分析<br>（' + (result[i].powerSupply==1 ? '单相制' : result[i].wiring == 1?'三相四线制':'三相三线制') + '）</div>\n' +
                '<div class="text-emphasize">\n' +
                '<span class="font-p32 text-bolder">' + Math.round(health * 10) / 10 + '</span>\n' +
                '<span class="font-p12">分</span>\n' +
                '</div>\n' +
                '<img src="../customize/images/analysis-score.png" alt="">\n' +
                '</div>\n' +
                '<div class="chart" id="chart_radar' + i + '" style="height: 182px; width: 208px;"></div>\n' +
                '</div>\n' +
                '</div>\n' +
                '<a class="link" onclick=\"toDeviceDataPage(' + result[i].id + ')\" title="查看设备数据"><i class="iconfont icon-chakanxiangqing"></i></a>\n' +
                '</div>';
            $('#device_List').append(str);
            var data = result[i];
            var dataArray = new Array();
            var chart_radar = echarts.init(document.getElementById('chart_radar' + i));
            chart_radar.setOption(option_radar);
            if (data) {
                /*如果powerSupply==1 就是单相电*/
                if (result[i]['powerSupply'] == 1) {
                    dataArray.push(Math.round(data.voltageDeviation * 10) / 10);
                    dataArray.push(Math.round(data.frequencyDeviation * 10) / 10);
                    dataArray.push(Math.round(data.loadRate * 10) / 10);
                    dataArray.push(Math.round(data.powerFactor * 10) / 10);
                    chart_radar.setOption({//用电分析
                        radar: {
                            center: ['50%', '50%'],
                            radius: '76%',
                            indicator: [
                                {name: '电压偏差', max: 100},
                                {name: '频率\n偏差', max: 100},
                                {name: '负载率', max: 100},
                                {name: '功率\n因数', max: 100}
                            ],
                        },
                        series: [{
                            data: [{
                                value: dataArray
                            }]
                        }]
                    });
                } else {
                    dataArray.push(Math.round(data.voltageDeviation * 10) / 10);
                    dataArray.push(Math.round(data.frequencyDeviation * 10) / 10);
                    dataArray.push(Math.round(data.unblance * 10) / 10);
                    dataArray.push(Math.round(data.loadRate * 10) / 10);
                    dataArray.push(Math.round(data.powerFactor * 10) / 10);
                    chart_radar.setOption({//用电分析
                        series: [{
                            data: [{
                                value: dataArray
                            }]
                        }]
                    });
                }
            }
        }
        setPage($('#page'), pageIndex, pages, total, function (num) {
            $.cookie("deviceCookieNum", num, {path: '/'});
            loadDeviceListData(num);
        });
        window.parent.changeIframeH();
        hideLoading();
        //}
    })
}

function set_paging(e) {
    $("#page").paging({
        pageNo: 1,
        totalPage: Math.ceil(e / 10),
        totalSize: e,
        callback: function (num) {
            set_tr(num);
        }
    });
    set_tr(1);

    if (e < 1) {
        $('device_List').empty();
        $("device_List").append($("<tr><td align='center' colspan='15'>选择条件内无数据</td></tr>"));
    }
}

function set_tr(e) {
    var start = (e - 1) * 10 + 1;
    var end = e * 10;
    $('.device-list').addClass('d-none');
    for (var i = start; i <= end; i++) { // tr_len是要控制的tr个数
        $("#tr_" + i).removeClass('d-none');
    }
}

$("#page").paging({
    pageNo: 1,
    totalPage: 1,
    totalSize: 0,
    callback: function (num) {
    }
});


/*状态筛选切换*/
$('#status_switch_wrapper button').click(function () {
    $(this).addClass('active').siblings().removeClass('active');
})

/*设备图片加载失败，展示默认图片*/
function deviceImgError(e) {
    $(e).prop('src', '../customize/images/no-photo.png');
}

/*点击设备图片，展示基本信息弹窗*/
function viewDeviceInfo(id) {
    /*根据ID查询信息*/
    getJson("/deviceData/getProduceDeviceById", {"id": id}, 'GET', function (result) {
        if (result.status == 200) {
            var data = result.data;
            $('#name-id').text(data.name);
            $('#sn-id').text(data.sn);
            $('#ceqNumber-id').text(data.ceqNumber);
            $('#port-id').text(data.port);
            $('#maintenanceCycle-id').text(data.maintenanceCycle + "天");
            $('#minPrice-id').text(data.minPrice + '元/kWh');
            $('#maxPrice-id').text(data.maxPrice + '元/kWh');
            $('#avgPrice-id').text(data.avgPrice + '元/kWh');
            $('#maxU-id').text(data.maxU + 'V');
            $('#maxI-id').text(data.maxI + 'A');
            $('#maxC-id').text(data.maxC + 'kWh');
            $('#standardU-id').text(data.standardU + 'V');
            $('#standardI-id').text(data.standardI + 'A');
            $('#standardC-id').text(data.standardC + 'kWh');
            $('#standardPower-id').text(data.standardPower + "kW");
            $('#qddl_id').text(data.iah + "kW");
            // $('#djdl_id').text(data.ial + "A");
            $('#dlb').text(data['currentRatio']);
            $('#createTime').text(getDate(data['createTime']).datetime());
            var deviceType = '';
            if (data['typeOneName']) {
                deviceType += data['typeOneName'];
                if (data['typeTowName']) {
                    deviceType += '/' + data['typeTowName'];
                    if (data['typeThreeName']) {
                        deviceType += '/' + data['typeThreeName'];
                    }
                }
            }
            $('#deviceType').text(deviceType);
            if (!isNull(data.image)) {
                $('#logo-id').attr('src', fileUrl + data.image);
                $('#logo-id')[0].onerror = function () {//加载出错时，替换为默认图
                    $(this).attr('src', '../customize/images/no-photo.png');
                }
            } else {//为空时，替换为默认图
                $('#logo-id').attr('src', '../customize/images/no-photo.png');
            }
        } else {
            myAlert("提示", "加载设备数据失败");
        }
    })
    $('#viewInfoModal').modal();
}

var option_radar = {//用电分析
    color: '#1890FF',
    tooltip: {
        backgroundColor: 'rgba(39, 71, 105, 0.7)'
    },
    radar: {
        name: {
            textStyle: {
                color: '#fff',
                lineHeight: 14
            }
        },
        nameGap: 8,
        center: ['50%', '57%'],
        radius: '75%',
        indicator: [
            {name: '电压偏差', max: 100},
            {name: '频率\n偏差', max: 100},
            {name: '三相不平衡', max: 100},
            {name: '负载率', max: 100},
            {name: '功率\n因数', max: 100}
        ],
        axisLine: {
            lineStyle: {
                color: '#D1E6F9'
            }
        },
        splitLine: {
            lineStyle: {
                color: ['#707070']
            }
        },
        splitArea: {
            areaStyle: {
                color: ['rgba(250,250,250,0.1)', 'rgba(200,200,200,0.1)']
            }
        }
    },
    series: [{
        name: '用电分析',
        type: 'radar',
        showSymbol: false,
        areaStyle: {
            color: 'rgba(13, 98, 177, 0.3)'
        },
        lineStyle: {
            color: '#1890FF',
            width: 2
        },
        // label: {
        //   show: true,
        //   formatter: '{c}'
        // },
        data: [{
            value: [0, 0, 0, 0, 0]
        }]
    }]
};

function toDeviceDataPage(deviceId) {
    var url = 'deviceData.html?deviceId=' + deviceId;
    parent.toSubPage(url);
}

